--#include "data\config\common\CommonFreshConfig.lua" once
--#include "data\config\activityconfig\DailyActivity\TwelvePalacesConfig.lua" once   --十二星宫
--#include "data\functions\Common\CommonBoss.lua" once				--BOSS通用功能"

--[[TwelvePalacesActorRankColumn = 
{	
	{"maxFloor"},				--0，玩家到达的最大楼层
	{"getFloorAwards"},			--1, 玩家领取到达第N层的奖励情况 格式{[3]=1, [6]=1, [9]=1, [12]=1}
}

TwelvePalacesActorRank = Lang.Rank.TwelvePalacesActorRank		--十二星宫玩家
]]
--[[
获取十二星宮某层中的怪物数量
]]
function GetTwelvePalacesFloorMonsterNum(floorIdx )
	--print("GetTwelvePalacesFloorMonsterNum, floorIdx="..floorIdx)
	local floorCfg = TwelvePalacesCfg.floors[floorIdx]		--从第1层开始
	if not floorCfg then
		return
	end

    local  counts = 0
	for i, bossCfg in ipairs( floorCfg.monsters or {} ) do
		local num = System.getMonsterCountById( bossCfg.monsterId, bossCfg.sceneId, 0 )
        counts = counts + num
	end

	return counts
end

--[[
获取十二星宮某层中的BOSS数量
]]
function GetTwelvePalacesFloorBossNum(floorIdx )
	--print("GetTwelvePalacesFloorBossNum, floorIdx="..floorIdx)
	local floorCfg = TwelvePalacesCfg.floors[floorIdx]		--从第1层开始
	if not floorCfg then
		return
	end
    local  counts =  0
	for i, bossCfg in ipairs( floorCfg.boss or {} ) do
		local num = System.getMonsterCountById( bossCfg.monsterId, bossCfg.sceneId, 0 )
        counts = counts + num
	end

	return counts
end

--[[
获取某层怪和BOSS的总数
]]
function GetTwelPFloorBoosAndMonsterAllNum(floorIdx)
	local floorCfg = TwelvePalacesCfg.floors[floorIdx]		--从第1层开始
	if not floorCfg then
		return
	end
    local  Num = System.getMonsterCountById( 0, floorCfg.sceneId, 0 ) or 0
    --print("GetTwelPFloorBoosAndMonsterAllNum, floorIdx="..floorIdx.." Num= "..Num)
	return Num
end

--[[
广播boss事件信息
type： 1：mob  2：die
]]
function TwelevePalacesBroadcastBossEvent( type, monId, lastHitKiller  )
	for monsterIdx,monsterId in ipairs(TwelvePalacesCfg.MonstersCfg.boss) do
		if monId == monsterId then
			local bossName = System.getMonsterNameById(monId)			--BOSS名字，去掉数字
			if type == 1 then
                System.broadcastTipmsg( string.format( Lang.ScriptTips.TwelvePalacesBossMobMsg01, bossName), ttScreenCenter + ttChatWindow)
			else
				if not lastHitKiller then
					return
				end
				System.broadcastTipmsg( string.format( Lang.ScriptTips.TwelvePalacesBossKillMsg01, bossName, Actor.getName( lastHitKiller)), ttScreenCenter + ttChatWindow )
			end
		end
	end
end

function TwelvelpalacesBroadcastToPlayer( monster, monId )
	local sid = Actor.getSceneId(monster)
	local playerList = LuaHelp.getSceneActorListById( sid ) or {}
	for i,player in ipairs( playerList ) do
		--print("notify monster ..")
		ChangeTwelvePalacesRightPanel(player)
	end
end

--[[
十二星宫某层怪物mob
]]
function OnTwelevePalacesMonsterMob(monster, monId, sceneId, x, y)
	--print("OnTwelevePalacesMonsterMob .. sceneId= "..sceneId)
	TwelvelpalacesBroadcastToPlayer( monster, monId )
	TwelevePalacesBroadcastBossEvent( 1, monId, nil )
end

--[[
十二星宫某层怪物die
]]
function OnTwelevePalacesMonsterDie(monster, sysarg, monId, lastHitKiller )
	--print("OnTwelevePalacesMonsterDie ..")
	TwelvelpalacesBroadcastToPlayer( monster, monId )
	TwelevePalacesBroadcastBossEvent( 2, monId, lastHitKiller )
end

function GmDoTwelvePalaces( sysarg, flag, param )
	--print("GmDoTwelvePalaces, flag="..flag..", param="..param)
	if flag == 1 then
		if param == 0 then
			--StopTwelvePalaces()
			CleanTwelvePalacesAwardInfo( sysarg )
		else
			--StartTwelvePalaces()
		end
	elseif flag == 2 then
		--local actorId = Actor.getActorId( sysarg )
		--local str = GetCommonRankColumnValueById(actorId, TwelvePalacesActorRank, 1) or 0
		--print("GmDoTwelvePalaces, str="..str)
	end
end


----------------------------------------------------------------
--[[
注册timer的函数，并将其注册到定时器
]]
function TwelvelpalacesTimerFreshProc(relatedFloors)
	for relatedFloorIdx,relatedFloor in ipairs(relatedFloors) do
		--print("TwelvelpalacesTimerFreshProc relatedFloor: "..relatedFloor)
		CommonFreshByFreshIdx(relatedFloor,0)
	end
end
function TwelvePalacesTimer1Func()
	local oneTimer = TwelvePalacesCfg.freshTimers[1] 
	if not oneTimer then
		return
	end
	TwelvelpalacesTimerFreshProc(oneTimer.relatedFloors) 
end
function TwelvePalacesTimer2Func()
	local oneTimer = TwelvePalacesCfg.freshTimers[2] 
	if not oneTimer then
		return
	end
	TwelvelpalacesTimerFreshProc(oneTimer.relatedFloors) 
end
function TwelvePalacesTimer3Func()
	local oneTimer = TwelvePalacesCfg.freshTimers[3] 
	if not oneTimer then
		return
	end
	TwelvelpalacesTimerFreshProc(oneTimer.relatedFloors) 
end
function TwelvePalacesTimer4Func()
	local oneTimer = TwelvePalacesCfg.freshTimers[4] 
	if not oneTimer then
		return
	end
	TwelvelpalacesTimerFreshProc(oneTimer.relatedFloors) 
end
function TwelvePalacesTimer5Func()
	local oneTimer = TwelvePalacesCfg.freshTimers[5] 
	if not oneTimer then
		return
	end
	TwelvelpalacesTimerFreshProc(oneTimer.relatedFloors) 
end
--[[
function TwelvePalacesTimer6Func()
	local oneTimer = TwelvePalacesCfg.freshTimers[6] 
	if not oneTimer then
		return
	end
	TwelvelpalacesTimerFreshProc(oneTimer.relatedFloors) 
end
function TwelvePalacesTimer7Func()
	local oneTimer = TwelvePalacesCfg.freshTimers[7] 
	if not oneTimer then
		return
	end
	TwelvelpalacesTimerFreshProc(oneTimer.relatedFloors) 
end
]]
--------------------------------------------------------------
--[[
此处注册7个timer的函数，规定大小为7个（配置文件严格配置）
]]
function OnTwelveTimerFuncProc( )
	--print("OnTwelveTimerFunc .. ")
	local NpcPtr = System.getGlobalNpc()
	
	--对所有定时器注册函数
	for timerIdx, oneTimer in ipairs(TwelvePalacesCfg.freshTimers) do
		local freshCd = oneTimer.freshCd
		if not freshCd then
			return
		end
        local funName = "TwelvePalacesTimer"..tostring(timerIdx).."Func"
        --print("OnTwelveTimerFuncProc "..funName)
        Actor.unregScriptCallback(NpcPtr, funName)
        Actor.regScriptTimer(NpcPtr, 0, 0, freshCd*1000, -1, funName)
	end
end



--[[
注册一些事件
]]
function TwelvePalacesResisterProc()
	--print("TwelvePalacesResisterProc...")
	for floorIdx, floorCfg in ipairs( TwelvePalacesCfg.floors ) do
		if floorCfg.checkItem[1] then
			ItemAddDispatcher.register( floorCfg.checkItem[1], TwelvePalacesOnItemAdd )				--注册获得某个道具触发的事件
		end
	end
	--注意：先注册定时器的函数方法，再注册monster的mob和die方法
    OnTwelveTimerFuncProc( )
	--print("CommonFreshRegisterMonsterFunc before...")

	--根据CommonFreshConfig配置文件进行注册,按照实际配置全部注册
	for index=1 , #CommonFreshConfig do
		CommonFreshRegisterMonsterFunc( index, OnTwelevePalacesMonsterMob, OnTwelevePalacesMonsterDie, nil, nil )
	end

end

function TwelvePalacesOnItemAdd( sysarg, itemId, itemCount )
	--print("TwelvePalacesOnItemAdd， itemId="..itemId..", itemCount=itemCount")
	local sceneId = Actor.getSceneId( sysarg )
	if not IsInTwelvePalaces( sceneId ) then
		return
	end
	--ChangeTwelvePalacesRightPanel( sysarg )
end

--[[function InitTwelvePalacesRank()
	--print("*****>>InitTwelvePalacesRank...")
	Rank.Init(TwelvePalacesActorRank, TwelvePalacesActorRank, TwelvePalacesActorRankColumn, 1000, 0)
end
]]


--活动开启
--[[function StartTwelvePalaces()
	ClearCommonRank( TwelvePalacesActorRank )		--清除排行榜

	local dVar = System.getDyanmicVar()
	dVar.TwelvePalacesBeginTime  = System.getCurrMiniTime()			--活动开启时间

	local NpcPtr = System.getGlobalNpc()
	Actor.unregScriptCallback(NpcPtr, "StopTwelvePalaces")
	Actor.unregScriptCallback(NpcPtr, "OnTwelvePalacesFreshMonsterLoop")    --终止刷小怪定时器
	Actor.unregScriptCallback(NpcPtr, "OnTwelvePalacesFreshBossLoop")    	--终止刷BOSS定时器
	Actor.unregScriptCallback(NpcPtr, "OnTwelvePalacesSynTimeLoop")    		--终止同步时间定时器

	Actor.regScriptTimer(NpcPtr, 0, TwelvePalacesCfg.timer.activityTime*1000, TwelvePalacesCfg.timer.activityTime*1000, 1, 
		"StopTwelvePalaces")
	Actor.regScriptTimer(NpcPtr, 0, 0, TwelvePalacesCfg.timer.monsterFreshCd*1000, -1, "OnTwelvePalacesFreshMonsterLoop")
	Actor.regScriptTimer(NpcPtr, 0, 0, TwelvePalacesCfg.timer.bossFreshCd*1000, -1, "OnTwelvePalacesFreshBossLoop")
	Actor.regScriptTimer(NpcPtr, 0, 0, 120*1000, -1, "OnTwelvePalacesSynTimeLoop")

	TickTwelvePalacesPlayerOut()			--T出残留的玩家
	System.broadcastTipmsg( Lang.ScriptTips.Twelvelpalaces08, ttScreenCenter + ttChatWindow )	
end]]

--[[活动结束
此方法，由定时器触发
]]
--[[function StopTwelvePalaces()
	local dVar = System.getDyanmicVar()
	dVar.TwelvePalacesBeginTime = nil
	local NpcPtr = System.getGlobalNpc()
	Actor.unregScriptCallback(NpcPtr, "StopTwelvePalaces")
	Actor.unregScriptCallback(NpcPtr, "OnTwelvePalacesFreshMonsterLoop")    --终止刷小怪定时器
	Actor.unregScriptCallback(NpcPtr, "OnTwelvePalacesFreshBossLoop")    	--终止刷BOSS定时器
	Actor.unregScriptCallback(NpcPtr, "OnTwelvePalacesSynTimeLoop")    		--终止同步时间定时器


	TickTwelvePalacesPlayerOut()					--T出残留的玩家
	ClearTwelvePalacesAllMonsters() 				--清理怪物
end]]

--[[
记录玩家到达最大层和奖励信息信息
]]
function TwelvePalacesBeforeEnter( sysarg)
	--print("TwelvePalacesBeforeEnter ..")
	local sVar = Actor.getStaticVar(sysarg)
	if not sVar.TwelvePalacesAward then
       sVar.TwelvePalacesAward = {}     --记录指定层发放的奖励情况（每天只发放一次）
	end 

	return true
end

--[[
清理玩家到达奖励信息
]]
function CleanTwelvePalacesAwardInfo(sysarg)
	local sVar = Actor.getStaticVar(sysarg)
	sVar.TwelvePalacesAward = nil
end

--[[
进入第N层
]]
function EnterTwelvePalacesFloor( sysarg )
	--[[if not IsTwelvePalacesValidTime() then
		Actor.sendTipmsg(sysarg, Lang.ScriptTips.COM0038, ttFlyTip)
		return
	end]]

	local sceneId = Actor.getSceneId( sysarg )
	if IsInTwelvePalaces( sceneId ) then
		Actor.sendTipmsg(sysarg, Lang.ScriptTips.COM0032, ttFlyTip)
		return false
	end

	local floorCfg = TwelvePalacesCfg.floors[1]
	if not floorCfg then
		return
	end

	if CommonEnterScence( sysarg, floorCfg, 0, " ", nil, TwelvePalacesBeforeEnter ) then
		local sVar = Actor.getStaticVar(sysarg)
	    sVar.TwelvePalacesEnterTime  = System.getCurrMiniTime()			--进入时间

        --注册回城的延迟消息
		Actor.removeEntityScriptDelayMsg( sysarg, 17 )
		--[[最后的true表示实体死亡，消息保留]]
		Actor.postEntityScriptDelayMsg( sysarg, TwelvePalacesCfg.timer.activityTime*1000, 0, 17,0,0,0,0,false,true )

		InitTwelePalacesRightPanel( sysarg )

		
		--注意要用enDailyOpTimes_XXX系列的定义
		--检查每天最大进行N次
		if CheckActorDailyDoneTimes( sysarg, enDailyOpTimes_TwelvePalace, 0, 1 ) then
			AddActorDailyDoneTimes( sysarg, enDailyOpTimes_TwelvePalace, 0, 1 )
			--print("EnterTwelvePalacesFloor, first do...")
		end
	end
end

function TwelePalacesCheckEnterFunc( sysarg, sceneCfg )
	--print(" TwelePalacesCheckEnterFunc... ")
	if sceneCfg.needConsume then
		--print(" TwelePalacesCheckEnterFunc, needConsume ")
		if not CheckConsumeCond( sysarg, sceneCfg.needConsume, 1, sceneCfg.sendTipmsg  ) then
			return false
		end

		if not DoConsumeCond( sysarg, sceneCfg.needConsume, 1, GameLog.clTwelvePalacesEnterFee, Lang.ScriptTips.TwelvelpalacesLog01, 
			sceneCfg.sendTipmsg ) then
			return false
		end
	end
	return true
end

--[[
进入下一层
flag:1-1-道具进入，2-元宝进入
]]
function EnterTwelePalacesNextFloor( sysarg, flag )
	--[[if not IsTwelvePalacesValidTime() then  		--不在活动时间内
		Actor.sendTipmsg(sysarg, Lang.ScriptTips.COM0038, ttFlyTip)
		return
	end]]

	local sceneId = Actor.getSceneId( sysarg )
	--print("EnterTwelePalacesNextFloor, flag="..flag..", sceneId="..sceneId)
	if not IsInTwelvePalaces( sceneId ) then
		return
	end

	local floorCfg 	= GetTwelePalacesFloorCfgBySceneId( sceneId )		--当前楼层
	if not floorCfg then
		return
	end


    if GetTwelPFloorBoosAndMonsterAllNum(floorCfg.floorIdx) > 0 then
        Actor.sendTipmsg(sysarg, Lang.ScriptTips.Twelvelpalaces10, ttFlyTip)
        return
    end
	

	local nextFloorIdx = floorCfg.floorIdx + 1							--下一层楼层
	--print("EnterTwelePalacesNextFloor, floorIdx="..floorCfg.floorIdx..", nextFloorIdx="..nextFloorIdx)
	local nextFloorCfg 	= TwelvePalacesCfg.floors[nextFloorIdx]
	if not nextFloorCfg then						--不存在该楼层
		Actor.sendTipmsg(sysarg, Lang.ScriptTips.Twelvelpalaces09, ttFlyTip)
		return
	end

	if CommonEnterScence( sysarg, nextFloorCfg, 0, " ", nil, nil ) then
		InitTwelePalacesRightPanel( sysarg ) 			--重新打开面板，因为title变化了
		Actor.closeNPCDialog( sysarg )					--关闭NPC面板
	end
end

function GetTwelePalacesFloorCfgBySceneId( sceneId )
	for i,floorCfg in ipairs( TwelvePalacesCfg.floors ) do
		if floorCfg.sceneId == sceneId then
			return floorCfg
		end
	end
	return nil
end

--[[
初始化右侧面板
]]
function InitTwelePalacesRightPanel( sysarg )
	local sceneId = Actor.getSceneId( sysarg )
	if not IsInTwelvePalaces( sceneId ) then			--不在星宫内
		return
	end

	local floorCfg 	= GetTwelePalacesFloorCfgBySceneId( sceneId )		--当前楼层
	if not floorCfg then
		return
	end

	local activityType 		= 2 			--活动
	local restTime 			= GetTwelvePalacesLastTime( sysarg )
	
	local panelInfo 		= {}
	panelInfo.sts 			= 1  				--进行中

	panelInfo.title 		= Lang.ScriptTips.TwelvelpalacesName 	--Fuben.getSceneNameById( sceneId )
	panelInfo.timeTitle 	= Lang.ScriptTips.panelCont01			--剩余时间
	panelInfo.restTime		= restTime

	panelInfo.contentTitle 	= Lang.ScriptTips.panelCont11  			--"本层信息"
	panelInfo.contents 		= {}
	panelInfo.contents[1]	= string.format( Lang.ScriptTips.panelCont10, floorCfg.floorIdx )

	local topFloorIdx = GetTwelvePalacesTopFloorIdx()
	if floorCfg.floorIdx < topFloorIdx then 		--非顶层
		--[[local checkItemId		= floorCfg.checkItem[1]
		local checkItemCount	= floorCfg.checkItem[2]
		local itemName			= Item.getItemName( checkItemId )
		local itemCount 		= Actor.getItemCount( sysarg, checkItemId )
		if itemCount > checkItemCount then
			itemCount = checkItemCount
		end
		panelInfo.contents[2]	= string.format( Lang.ScriptTips.panelCont12, itemName, itemCount, checkItemCount )
		]]
		panelInfo.contents[2]  = string.format( Lang.ScriptTips.Twelvelpalaces11, GetTwelPFloorBoosAndMonsterAllNum(floorCfg.floorIdx))
		panelInfo.buttons = {1,8}	--1：退出副本，2-单倍领奖，3-双倍领奖，4-查看排行榜，5-押镖寻路, 6-打开答题面板，7-放弃押镖，8-寻找活动NPC
	else
		panelInfo.buttons = {1}	--1：退出副本，2-单倍领奖，3-双倍领奖，4-查看排行榜，5-押镖寻路, 6-打开答题面板，7-放弃押镖，8-寻找活动NPC
	end

	panelInfo.awardTitle	= ""			--没有此title
	panelInfo.awards 		= {}			--没有可显示的奖励

	OpenActivityRightPanel( sysarg, activityType, enRightPanelActivity_12Palaces, panelInfo )
end

function ChangeTwelvePalacesRightPanel( sysarg )
	--print("ChangeTwelvePalacesRightPanel ..")
	local sceneId = Actor.getSceneId( sysarg )
	if not IsInTwelvePalaces( sceneId ) then			--不在星宫内
		return
	end

	local floorCfg 	= GetTwelePalacesFloorCfgBySceneId( sceneId )		--当前楼层
	if not floorCfg then
		return
	end

	local panelInfo 		= {}
	panelInfo.sts 			= 1  				--1-进行中,2-已结束
	panelInfo.contents 		= {}
	panelInfo.contents[1]	= string.format( Lang.ScriptTips.panelCont10, floorCfg.floorIdx )

	local topFloorIdx = GetTwelvePalacesTopFloorIdx()
	if floorCfg.floorIdx < topFloorIdx then 		--非顶层
		--[[local checkItemId		= floorCfg.checkItem[1]
		local checkItemCount	= floorCfg.checkItem[2]
		local itemName			= Item.getItemName( checkItemId )
		local itemCount 		= Actor.getItemCount( sysarg, checkItemId )
		if itemCount > checkItemCount then
			itemCount = checkItemCount
		end]]
		panelInfo.contents[2]  = string.format( Lang.ScriptTips.Twelvelpalaces11, GetTwelPFloorBoosAndMonsterAllNum(floorCfg.floorIdx))
		panelInfo.buttons = {1,8}	--1：退出副本，2-单倍领奖，3-双倍领奖，4-查看排行榜，5-押镖寻路, 6-打开答题面板，7-放弃押镖，8-寻找活动NPC
	else
		panelInfo.buttons = {1}	--1：退出副本，2-单倍领奖，3-双倍领奖，4-查看排行榜，5-押镖寻路, 6-打开答题面板，7-放弃押镖，8-寻找活动NPC
	end

	ChangeActivityRightPanel(sysarg, panelInfo)
end


function GetTwelvePalacesLastTime( sysarg )
	local sVar = Actor.getStaticVar( sysarg )
	if not sVar.TwelvePalacesEnterTime then 		--玩家进入时间
		return 0
	end

	local now = System.getCurrMiniTime()	
	local lastTime = sVar.TwelvePalacesEnterTime + TwelvePalacesCfg.timer.activityTime - now
	if lastTime > 0 then
		return lastTime
	end
	return 0
end

function GetTwelvePalacesTopFloorIdx()
	return #TwelvePalacesCfg.floors
end

--[[
刷出十二星宫某层的BOSS
]]
function FreshTwelvePalacesFloorBoss( floorIdx )
	--print("FreshTwelvePalacesFloorBoss, floorIdx="..floorIdx)
	local floorCfg = TwelvePalacesCfg.floors[floorIdx]		--从第1层开始
	if not floorCfg then
		return
	end

	for i, bossCfg in ipairs( floorCfg.boss or {} ) do
		freshSceneOneMonsterInRange( bossCfg )
	end
end

--[[
刷出十二星宫某层的小怪
]]
function FreshTwelvePalacesFloorMonsters( floorIdx )
	--print("FreshTwelvePalacesFloorMonsters, floorIdx="..floorIdx)
	local floorCfg = TwelvePalacesCfg.floors[floorIdx]		--从第1层开始
	if not floorCfg then
		return
	end

	for i, monCfg in ipairs( floorCfg.monsters or {} ) do
		freshSceneOneMonsterInRange( monCfg )
	end
end

--[[
刷出十二星宫怪物
]]
function FreshTwelvePalacesMonsters( )
	--print("FreshTwelvePalacesMonsters...")
	for i, floorCfg in ipairs( TwelvePalacesCfg.floors ) do
		FreshTwelvePalacesFloorMonsters( i )
	end
end

--[[
刷出十二星宫BOSS
]]
function FreshTwelvePalacesBoss( )
	--print("FreshTwelvePalacesBoss...")
	for i, floorCfg in ipairs( TwelvePalacesCfg.floors ) do
		FreshTwelvePalacesFloorBoss( i )
	end
end

function ClearTwelvePalacesAllMonsters()
	for i, floorCfg in ipairs( TwelvePalacesCfg.floors ) do
		for i, monCfg in ipairs( floorCfg.monsters or {} ) do
			clearScenceMonster( monCfg ) 		--清除小怪
		end

		for i, bossCfg in ipairs( floorCfg.boss or {} ) do
			clearScenceMonster( bossCfg )		--清除BOSS
		end
	end
end

function OnTwelvePalacesFreshMonsterLoop(  )
	--print("OnTwelvePalacesFreshMonsterLoop...")
	FreshTwelvePalacesMonsters( )
end

function OnTwelvePalacesFreshBossLoop(  )
	--print("OnTwelvePalacesFreshBossLoop...")
	FreshTwelvePalacesBoss( )
end

--[[
同步时间
]]
--[[function OnTwelvePalacesSynTimeLoop()
	local restTime 	= GetTwelvePalacesLastTime()
	--print("OnTwelvePalacesSynTimeLoop， restTime="..restTime)
	for i,floorCfg in ipairs( TwelvePalacesCfg.floors ) do
		local playerList = LuaHelp.getSceneActorListById( floorCfg.sceneId ) or {}
		for i, player in ipairs( playerList or {} ) do
			SynTimeActivityRightPanel( player, enRightPanelActivity_12Palaces, restTime )
		end
	end
end]]

--[[
从外部进入到十二星宫、从十二星宫离开、在十二星宫中下线，需要清除道具
合法途径进入：在十二星宫中转移，不清理道具
非法途径进入：在十二星宫中转移，要清理道具
]]
function ClearTwelvePalacesItems( sysarg )
	for i,itemId in ipairs( TwelvePalacesCfg.itemsNeedClear ) do
		RemoveActorItemInBag( sysarg, itemId, GameLog.clTwelvePalacesCLearItem, Lang.ScriptTips.TwelvelpalacesLog03 )
	end
end

--[[
广播顶层排行榜信息
]]
--[[function TwelvePalacesBroadcast(  )
	--print("TwelvePalacesBroadcast...")
end]]

--[[
十二星宫内场景变化
可能是从外面进入，可能是内部楼层切换，可能是退出活动
]]
function TwelvePalacesOnChange( sysarg, nowSceneId, lastSceneId )
	--print("TwelvePalacesOnChange, nowSceneId="..nowSceneId..", lastSceneId="..lastSceneId)
	local nowSceneIs12Palace 	= IsInTwelvePalaces( nowSceneId )
	local lastSceneIs12Palace 	= IsInTwelvePalaces( lastSceneId )

	if not lastSceneIs12Palace and nowSceneIs12Palace  then
		OnEnterTwelvePalacesFromOutside( sysarg )					--从外面进入到十二星宫
	elseif lastSceneIs12Palace and nowSceneIs12Palace  then
		OnSwitchTwelvePalacesFloor( sysarg )  			--十二星宫活动内的场景切换
	elseif lastSceneIs12Palace and not nowSceneIs12Palace then
		OnExitTwelvePalaces( sysarg, lastSceneId ) 		--离开十二星宫活动
	end
	--Actor.closeDialogs( sysarg, enLinkTwelvePalacesAwardWnd)
end

--[[
玩家登陆时的处理
]]
function OnTwelvePalacesLogin( sysarg )
	ClearTwelvePalacesItems( sysarg )
end

--[[
进入十二星宫，通过外挂进入场景，也会触发这里
注意：删除道具放在这里，确保一定可以删除道具，以防玩家通过外挂进入
]]
function OnEnterTwelvePalacesFromOutside( sysarg )
	local sceneId = Actor.getSceneId( sysarg )
	--print("OnEnterTwelvePalacesFromOutside, sceneId="..sceneId)
	if not IsInTwelvePalaces( sceneId ) then
		return
	end
	ClearTwelvePalacesItems( sysarg )
end

--[[十二星宫活动内的场景切换
已经进入新的楼层
]]
function OnSwitchTwelvePalacesFloor( sysarg )
	local sceneId = Actor.getSceneId( sysarg )
	--print("OnSwitchTwelvePalacesFloor, sceneId="..sceneId)
	TwelvePalacesMailAward( sysarg )				--到达楼层发奖
	InitTwelePalacesRightPanel( sysarg )			--因为title变化了
end

--[[退出十二星宫的操作
完全离开十二星宫
]]
function OnExitTwelvePalaces( sysarg, lastSceneId ) 		--离开十二星宫活动
	--print("OnExitTwelvePalaces, lastSceneId="..lastSceneId)
	if not IsInTwelvePalaces( lastSceneId ) then
		return
	end

    --注销回城的延迟消息
	Actor.removeEntityScriptDelayMsg( sysarg, 17 )

	CloseActivityRightPanel(sysarg)

	local sVar = Actor.getStaticVar( sysarg )
	sVar.TwelvePalacesEnterTime = nil 		--清除玩家进入时间


	Actor.closeDialogs( sysarg, enLinkTwelvePalacesAwardWnd)
	ClearTwelvePalacesItems( sysarg )
end

--[[
是否在场景内
]]
function IsInTwelvePalaces( sceneId )
	--print("IsInTwelvePalaces, sceneId="..sceneId)
	for i,floorCfg in ipairs( TwelvePalacesCfg.floors ) do
		if sceneId == floorCfg.sceneId then
			return true
		end
	end
	return false
end

--[[
是否在活动中
]]
--[[function IsTwelvePalacesValidTime( )
	local now 	= System.getCurrMiniTime()
	local dVar 	= System.getDyanmicVar()
	if dVar.TwelvePalacesBeginTime and dVar.TwelvePalacesBeginTime > 0 and now-dVar.TwelvePalacesBeginTime >=0 and
		now-dVar.TwelvePalacesBeginTime < TwelvePalacesCfg.timer.activityTime then
		return true
	end
	return false
end]]

function ProcExitTwelvePalaces( sysarg )
	Actor.returnCity( sysarg )
end

--[[
获取指定层奖励
]]
function GetTwelvePalacesActorFloorAwardSts(sysarg, floorIdx )
	--print("GetTwelvePalacesActorFloorAwardSts..")
	local sVar = Actor.getStaticVar(sysarg)
	if not sVar.TwelvePalacesAward then
       sVar.TwelvePalacesAward = {}     --记录指定层发放的奖励情况（每天只发放一次）[跨日时可能出现被置为nil,此处再次初始化]
	end 
	return sVar.TwelvePalacesAward[floorIdx] or 0
	
end

--[[
设置指定层奖励
--newAwardSts={ [floorIdx]=1, }
]]
function SetTwelvePalacesActorFloorAwardSts( sysarg, floorIdx )
    --print("SetTwelvePalacesActorFloorAwardSts, str="..str)
	local sVar = Actor.getStaticVar(sysarg)
	if not sVar.TwelvePalacesAward then
		return 
	end
    sVar.TwelvePalacesAward[floorIdx] = 1
end

--[[
十二星宫内公告
]]
function BroadTwelvePalacesMsg( msg, flag )
	for i,floorCfg in ipairs( TwelvePalacesCfg.floors ) do
		BroadMsgInScence( floorCfg.sceneId, msg, flag)
	end
end

--[[
校验能否使用恶意钥匙
function CheckUseTwelvePalacesKey( sysarg )
	local sceneId = Actor.getSceneId( sysarg )
	if not IsInTwelvePalaces( sceneId ) then
		Actor.sendTipmsg(sysarg, Lang.Script.TwelvePalaces026, ttFlyTip)
		return false
	end

	if not IsTwelvePalacesValidTime() then
		Actor.sendTipmsg(sysarg, Lang.Script.TwelvePalaces027, ttFlyTip)
		return false
	end

	return true
end
]]

--踢出活动玩家
function TickTwelvePalacesPlayerOut()
	for i,floorCfg in ipairs( TwelvePalacesCfg.floors ) do
		local playerList = LuaHelp.getSceneActorListById( floorCfg.sceneId ) or {}
		for i, player in ipairs( playerList or {} ) do
			ProcExitTwelvePalaces( player )
		end
	end
end

--[[在十二星宫内复活
flag：1-元宝复活，2-安全复活
]]
function OnTwelvePalacesPlayerRelive( sysarg, flag )
	--print("OnTwelvePalacesPlayerRelive, flag="..flag)
	if flag == 2 then
		local maxHp = Actor.getIntProperty(sysarg, PROP_CREATURE_MAXHP)
		local hp = maxHp*0.1
		Actor.setUIntProperty(sysarg, PROP_CREATURE_HP, hp)
		--InitTwelePalacesRightPanel( sysarg )
	end

	local sceneId = Actor.getSceneId( sysarg )
	local floorCfg 	= GetTwelePalacesFloorCfgBySceneId( sceneId )		--当前楼层
	if not floorCfg then
		return
	end
	if not floorCfg then
		return
	end
	Actor.enterScene( sysarg, floorCfg.sceneId, floorCfg.pos[1], floorCfg.pos[2] )
end

--[[
返回值：0-BOSS之家之外，1-BOSS之家内（非顶层），2-BOSS之家内（顶层）
]]
function TwelvePalacesGetFloorSts( sceneId )
	local topSceneId = TwelvePalacesCfg.floors[#TwelvePalacesCfg.floors].sceneId 				--顶层场景
	for floorIdx, floorCfg in ipairs( TwelvePalacesCfg.floors ) do
		if floorCfg.sceneId == sceneId then
			if sceneId == topSceneId then
				return 2
			else
				return 1
			end
		end
	end
	return 0
end

--[[
退出十二星宫
]]
function TwelvePalacesQuit( sysarg )
	local sceneId = Actor.getSceneId( sysarg )
	if IsInTwelvePalaces( sceneId ) then
		Actor.returnCity( sysarg )
	end
end

--[[
通过邮件发通关奖励，如果不在场景、已经领取过、怪物尚未击杀完毕，则不发
]]
function TwelvePalacesMailAward( sysarg )
	--print("TwelvePalacesMailAward...")
	local sceneId = Actor.getSceneId( sysarg )
	local floorCfg 	= GetTwelePalacesFloorCfgBySceneId( sceneId )		--当前楼层
	if not floorCfg then
		return
	end

	local floorAwardsCfg = TwelvePalacesCfg.palaceAwards[floorCfg.floorIdx]
	if not floorAwardsCfg then
		return
	end

	local floorAwards = floorAwardsCfg.floorsAwards
	if not floorAwards then
		return
	end

	--local actorId = Actor.getActorId( sysarg )
	--print("TwelvePalacesMailAward, actorId="..actorId)

	local awardsSts = GetTwelvePalacesActorFloorAwardSts(sysarg , floorCfg.floorIdx)
	if awardsSts > 0 then
		--print("TwelvePalacesMailAward,  floor["..floorCfg.floorIdx.."] has given award")
		return
	else
		SetTwelvePalacesActorFloorAwardSts(sysarg, floorCfg.floorIdx ) 
	end

	--local actorLevel  		= Actor.getIntProperty(sysarg,PROP_CREATURE_LEVEL)
	--local transFloorAwards 	= TransAwardsByType( floorAwards, actorLevel )			--如果经验库经验，需要转换一下
	--if not transFloorAwards then
	--	return
	--end
	
	--发奖，进行经验库经验转换成属猪经验
	GiveCommonAward(sysarg, floorAwards, GameLog.clTwelvePalacesFloorAward, Lang.ScriptTips.TwelvelpalacesLog02)

	--[[
	local title 	= Lang.ScriptTips.TwelvelpalacesMailTitle
	local content 	= string.format( Lang.ScriptTips.TwelvelpalacesMailCont, floorCfg.floorIdx )
	Awards.GiveToMailById(actorId, transFloorAwards, title, content, GameLog.clTwelvePalacesFloorAward, Lang.ScriptTips.TwelvelpalacesLog02 )
	]]
	Actor.openDialogs( sysarg, enLinkTwelvePalacesAwardWnd, tostring(floorCfg.floorIdx))
	--print("floorIdx="..tostring(floorCfg.floorIdx))	
end

--零点刷新
--清除每层的monster，重新注册计时器
function OnTwelvelpalacesRefreshZero( )
	--print("OnTwelvelpalacesRefreshZero")
	for k, oneFresh in pairs(CommonFreshConfig) do
		--获取前一天的monster配置
		local theDayBefore = System.getDaysSinceOpenServer() - 1
		if theDayBefore <= 0 then
			theDayBefore = 1
		end 
		local oneCfg = nil
		for i, elem in ipairs( oneFresh.freshMonsters or {} ) do
			if elem.openServerDay[1] <= theDayBefore and theDayBefore <= elem.openServerDay[2] then
				oneCfg = elem
				break
			end
		end
		if oneCfg then
			for k,monster in pairs(oneCfg.monsters) do
				local hScene = Fuben.getSceneHandleById(monster.sceneId, 0)
				if hScene then
					Fuben.clearMonster(hScene,  monster.monsterId)
					Fuben.clearMonster(hScene,  1)   --此处清除墓碑怪
				end
			end
		end
	end
	
	--刷出顶层的BOSS(最后两个配置（14,15配置的BOSS）)
	for index= #CommonFreshConfig - 1 , #CommonFreshConfig do
		CommonFreshByFreshIdx( index, 0 )
	end

	--重新注册定时器
	OnTwelveTimerFuncProc( )   
end



TwelvePalacesResisterProc()			--注册一些事件
--InitTwelvePalacesRank()				--十二星宫排行榜


